package prickworlds.gui;

/**
 * Class to handle focus
 * 
 * @author Faruk Acibal, Richard Dziambor, Christian Holzreuter, Nicolas Winkler
 * 
 */
public class Focusable {

	/**
	 * the parent dealer of this control
	 */
	private FocusDealer focusDealer;

	/**
	 * <a>true</a> if this control is currently focused, <code>false</code>
	 * otherwise
	 */
	private boolean focused;

	/**
	 * creates a child focusable to a <link>FocusDealer</link>
	 * 
	 * @param focusDealer
	 *            the parent dealer
	 */
	public Focusable(FocusDealer focusDealer) {
		this.focusDealer = focusDealer;
		focused = false;
	}

	/**
	 * default constructor
	 */
	public Focusable() {
		focused = false;
		focusDealer = null;
	}

	/**
	 * checks weather this control is focused
	 * 
	 * @return <code>true</code> if focused, false otherwise
	 */
	public boolean isFocused() {
		return focused;
	}

	/**
	 * requests focus to the parent <link>FocusDealer</link>
	 * 
	 * @return <code>true</code> if the control is now focused,
	 *         <code>false</code> otherwise
	 */
	protected boolean requestFocus() {
		if (focusDealer == null) {
			focused = true;
			return true;
		} else {
			if (focusDealer.requestFocus(this)) {
				focused = true;
				return true;
			}
		}
		
		return false;
	}

	/**
	 * sets the parent <link>FocusDealer</link> to the specified value
	 * @param focusDealer the new parent <link>FocusDealer</link>
	 */
	public void setFocusDealer(FocusDealer focusDealer) {
		this.focusDealer = focusDealer;
	}

	/**
	 * invoked by the parent <link>FocusDealer</link> when the control loses focus
	 */
	protected void onFocusLoss() {
		focused = false;
	}
}